var websocket = function (opts) {
    var options = {
        identify: "demo",// 身份标识符
        token: "", // 访问token
        host: '127.0.0.1',
        port: 1990,
        interval: 3,
        onopen: function (event) {
            console.log("open", event);
        },
        onmessage: function (event) {
            console.log("message", event.data);
        },
        onclose: function (event) {
            console.log("close", event);
            return setTimeout(connect, options.interval);
        },
        onerror: function (event) {
            // 服务器断开时先onerror，再onclose
            console.log("error", event);
        }

    }, ws;
    // 初始化配置
    for (var x in opts) {
        options[x] = opts[x];
    }

    var send = function (msg) {
        if (typeof msg === "object") {
            msg = JSON.stringify(msg);
        } else {
            // msg = JSON.stringify({
            //     data: msg
            // });
        }
        ws && ws.send(msg);
    };
    var close = function () {
        ws && ws.close();
    };

    var connect = function () {
        ws = new WebSocket("ws://" + options.host + ":" + options.port);
        ws.onopen = function (event) {
            //发送登录信息
            send({
                action: "sign",
                identify: options.identify,
                token: options.token
            });
            options.onopen(event);
        };
        ws.onmessage = options.onmessage;
        ws.onclose = options.onclose;
        ws.onerror = options.onerror;
    };
    return {
        connect: connect,
        send: send,
        close: close
    };
};